// -*- c -*-
//
// %CopyrightBegin%
//
// Copyright Ericsson AB 2017-2022. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// %CopyrightEnd%
//

// ================================================================
// All guards with zero arguments have special instructions,
// for example:
//
// 	self/0
// 	node/0
//
// All other guard BIFs take one or two arguments.
// ================================================================

CALL_GUARD_BIF(BF, TmpReg, Dst) {
    Eterm result;
#ifdef DEBUG
    Eterm* orig_htop = HTOP;
    Eterm* orig_stop = E;
#endif

    ERTS_DBG_CHK_REDS(c_p, FCALLS);
    c_p->fcalls = FCALLS;
    PROCESS_MAIN_CHK_LOCKS(c_p);
    ASSERT(!ERTS_PROC_IS_EXITING(c_p));
    ERTS_CHK_MBUF_SZ(c_p);
    DEBUG_SWAPOUT;
    result = (*$BF)(c_p, $TmpReg, I);
    DEBUG_SWAPIN;
    ASSERT(orig_htop == HTOP && orig_stop == E);
    ERTS_CHK_MBUF_SZ(c_p);
    ASSERT(!ERTS_PROC_IS_EXITING(c_p) || is_non_value(result));
    ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
    PROCESS_MAIN_CHK_LOCKS(c_p);
    ERTS_HOLE_CHECK(c_p);
    FCALLS = c_p->fcalls;
    ERTS_DBG_CHK_REDS(c_p, FCALLS);
    if (ERTS_LIKELY(is_value(result))) {
        $Dst = result;
        $NEXT0();
    }
}

// Guard BIF in head. On failure, ignore the error and jump
// to the code for the next clause. We don't support tracing
// of guard BIFs.

i_bif1 := i_bif.fetch0.call;
i_bif2 := i_bif.fetch1.fetch0.call;
i_bif3 := i_bif.fetch2.fetch1.fetch0.call;

i_bif.head() {
    ErtsBifFunc bf;
    Eterm tmp_reg[3];
}

i_bif.fetch0(Src) {
    tmp_reg[0] = $Src;
}

i_bif.fetch1(Src) {
    tmp_reg[1] = $Src;
}

i_bif.fetch2(Src) {
    tmp_reg[2] = $Src;
}

i_bif.call(Fail, Bif, Dst) {
    bf = (BifFunction) $Bif;
    $CALL_GUARD_BIF(bf, tmp_reg, $Dst);

    $FAIL($Fail);
}

//
// Guard BIF in body. It can fail like any BIF. No trace support.
//

i_bif1_body := i_bif_body.fetch0.call;
i_bif2_body := i_bif_body.fetch1.fetch0.call;
i_bif3_body := i_bif_body.fetch2.fetch1.fetch0.call;

i_bif_body.head() {
    ErtsBifFunc bf;
    Eterm tmp_reg[3];
}

i_bif_body.fetch0(Src) {
    tmp_reg[0] = $Src;
}

i_bif_body.fetch1(Src) {
    tmp_reg[1] = $Src;
}

i_bif_body.fetch2(Src) {
    tmp_reg[2] = $Src;
}

i_bif_body.call(Bif, Dst) {
    bf = (BifFunction) $Bif;
    $CALL_GUARD_BIF(bf, tmp_reg, $Dst);

    reg[0] = tmp_reg[0];
    reg[1] = tmp_reg[1];
    reg[2] = tmp_reg[2];
    SWAPOUT;
    I = handle_error(c_p, I, reg, ubif2mfa((void *) bf));
    goto post_error_handling;
}

//
// length/1 is the only guard BIF that does not execute in constant
// time. Here follows special instructions to allow the calculation of
// the list length to be broken in several chunks to avoid hogging
// the scheduler for a long time.
//

i_length_setup(Live, Src) {
    Uint live = $Live;
    Eterm src = $Src;

    reg[live] = src;
    reg[live+1] = make_small(0);
    reg[live+2] = src;

    /* This instruction is always followed by i_length */
    SET_I($NEXT_INSTRUCTION);
    goto i_length_start__;
    //| -no_next
}

//
// This instruction can be executed one or more times. When entering
// this instruction, the X registers have the following contents:
//
// reg[live+0] The remainder of the list.
// reg[live+1] The length so far (tagged integer).
// reg[live+2] The original list. Only used if an error is generated
//             (if the final tail of the list is not []).
//

i_length := i_length.start.execute;

i_length.start() {
 i_length_start__:
    ;
}

i_length.execute(Fail, Live, Dst) {
    Eterm result;
    Uint live;

    ERTS_DBG_CHK_REDS(c_p, FCALLS);
    c_p->fcalls = FCALLS;
    PROCESS_MAIN_CHK_LOCKS(c_p);
    ASSERT(!ERTS_PROC_IS_EXITING(c_p));
    ERTS_CHK_MBUF_SZ(c_p);
    DEBUG_SWAPOUT;

    live = $Live;
    result = erts_trapping_length_1(c_p, reg+live);

    DEBUG_SWAPIN;
    ERTS_CHK_MBUF_SZ(c_p);
    ASSERT(!ERTS_PROC_IS_EXITING(c_p) || is_non_value(result));
    ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
    PROCESS_MAIN_CHK_LOCKS(c_p);
    ERTS_HOLE_CHECK(c_p);
    FCALLS = c_p->fcalls;
    ERTS_DBG_CHK_REDS(c_p, FCALLS);
    if (ERTS_LIKELY(is_value(result))) {
        /* Successful calculation of the list length. */
        $REFRESH_GEN_DEST();
        $Dst = result;
        $NEXT0();
    } else if (c_p->freason == TRAP) {
        /*
         * Good so far, but there is more work to do. Yield.
         */
        $SET_CP_I_ABS(I);
        SWAPOUT;
        c_p->arity = live + 3;
        c_p->current = NULL;
        goto context_switch3;
    } else {
        /* Error. */
        $BIF_ERROR_ARITY_1($Fail, BIF_length_1, reg[live+2]);
    }
    //| -no_next
}

//
// Call a BIF, store the result in x(0) and transfer control to the
// next instruction.
//
call_light_bif(Bif, Exp) {
    Export *export;
    ErtsBifFunc bf;

    Eterm result;
    ErlHeapFragment *live_hf_end;

    bf = (ErtsBifFunc) $Bif;
    export = (Export*) $Exp;

    if (!((FCALLS - 1) > 0 || (FCALLS-1) > neg_o_reds)) {
        /*
         * If we have run out of reductions, do a context
         * switch before calling the BIF.
         */
        c_p->arity = GET_EXPORT_ARITY(export);
        c_p->current = &export->info.mfa;
        goto context_switch3;
    }

    if (ERTS_UNLIKELY(export->is_bif_traced)) {
        $SAVE_CONTINUATION_POINTER($NEXT_INSTRUCTION);
        $DISPATCH_EXPORT(export);
    }

    ERTS_MSACC_SET_BIF_STATE_CACHED_X(GET_EXPORT_MODULE(export), bf);

    PRE_BIF_SWAPOUT(c_p);
    ERTS_DBG_CHK_REDS(c_p, FCALLS);
    c_p->fcalls = FCALLS - 1;
    if (FCALLS <= 0) {
        save_calls(c_p, export);
    }
    ASSERT(!ERTS_PROC_IS_EXITING(c_p));
    ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
    live_hf_end = c_p->mbuf;
    ERTS_CHK_MBUF_SZ(c_p);

    result = (*bf)(c_p, reg, I);

    /* Only heavy BIFs may GC. */
    ASSERT(E == c_p->stop);

    ERTS_CHK_MBUF_SZ(c_p);
    ASSERT(!ERTS_PROC_IS_EXITING(c_p) || is_non_value(result));
    ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
    ERTS_HOLE_CHECK(c_p);
    ERTS_REQ_PROC_MAIN_LOCK(c_p);
    if (ERTS_IS_GC_AFTER_BIF_DESIRED(c_p)) {
        Uint arity = GET_EXPORT_ARITY(export);
        result = erts_gc_after_bif_call_lhf(c_p, live_hf_end, result,
                                            reg, arity);
        E = c_p->stop;
    }
    HTOP = HEAP_TOP(c_p);
    FCALLS = c_p->fcalls;
    PROCESS_MAIN_CHK_LOCKS(c_p);
    ERTS_DBG_CHK_REDS(c_p, FCALLS);

    /*
     * We have to update the cache if we are enabled in order
     * to make sure no bookkeeping is done after we disabled
     * msacc. We don't always do this as it is quite expensive.
     */
    if (ERTS_MSACC_IS_ENABLED_CACHED_X()) {
        ERTS_MSACC_UPDATE_CACHE_X();
    }
    ERTS_MSACC_SET_STATE_CACHED_M_X(ERTS_MSACC_STATE_EMULATOR);
    if (ERTS_LIKELY(is_value(result))) {
        r(0) = result;
        CHECK_TERM(r(0));
        $NEXT0();
    } else if (c_p->freason == TRAP) {
        /*
         * Set the continuation pointer to return to next
         * instruction after the trap (either by a return from
         * erlang code or by nif_bif.epilogue() when the BIF
         * is done).
         */
        $SAVE_CONTINUATION_POINTER($NEXT_INSTRUCTION);
        SET_I(c_p->i);
        $DISPATCH();
    }

    /*
     * Error handling.  SWAPOUT is not needed because it was done above.
     */
    ASSERT(c_p->stop == E);
    I = handle_error(c_p, I, reg, &export->info.mfa);
    goto post_error_handling;
    //| -no_next
}

//
// Call a BIF tail-recursively, storing the result in x(0) and doing
// a return to the continuation pointer.
//
call_light_bif_only(Bif, Exp) {
    ErlHeapFragment *live_hf_end;
    ErtsBifFunc bf;
    Export *export;
    Eterm result;

    bf = (ErtsBifFunc) $Bif;
    export = (Export*) $Exp;

    if (!((FCALLS - 1) > 0 || (FCALLS-1) > neg_o_reds)) {
        /*
         * If we have run out of reductions, do a context
         * switch before calling the BIF.
         */
        c_p->arity = GET_EXPORT_ARITY(export);
        c_p->current = &export->info.mfa;
        goto context_switch3;
    }

    if (ERTS_UNLIKELY(export->is_bif_traced)) {
        /* Set up a dummy stack frame so we can perform a normal call. Loader
         * transformations ensure that the next instruction after this is
         * 'deallocate_return 0'. */
        $AH(0, 0, GET_EXPORT_ARITY(export));

        $SAVE_CONTINUATION_POINTER($NEXT_INSTRUCTION);
        $DISPATCH_EXPORT(export);
    }

    ERTS_MSACC_SET_BIF_STATE_CACHED_X(GET_EXPORT_MODULE(export), bf);

    PRE_BIF_SWAPOUT(c_p);
    ERTS_DBG_CHK_REDS(c_p, FCALLS);
    c_p->fcalls = FCALLS - 1;
    if (FCALLS <= 0) {
        save_calls(c_p, export);
    }
    ASSERT(!ERTS_PROC_IS_EXITING(c_p));
    ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
    live_hf_end = c_p->mbuf;
    ERTS_CHK_MBUF_SZ(c_p);

    result = (*bf)(c_p, reg, I);

    /* Only heavy BIFs may GC. */
    ASSERT(E == c_p->stop);

    ERTS_CHK_MBUF_SZ(c_p);
    ASSERT(!ERTS_PROC_IS_EXITING(c_p) || is_non_value(result));
    ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
    ERTS_HOLE_CHECK(c_p);
    ERTS_REQ_PROC_MAIN_LOCK(c_p);
    if (ERTS_IS_GC_AFTER_BIF_DESIRED(c_p)) {
        Uint arity = GET_EXPORT_ARITY(export);
        result = erts_gc_after_bif_call_lhf(c_p, live_hf_end, result,
                                            reg, arity);
        E = c_p->stop;
    }
    HTOP = HEAP_TOP(c_p);
    FCALLS = c_p->fcalls;
    PROCESS_MAIN_CHK_LOCKS(c_p);
    ERTS_DBG_CHK_REDS(c_p, FCALLS);

    /*
     * We have to update the cache if we are enabled in order
     * to make sure no bookkeeping is done after we disabled
     * msacc. We don't always do this as it is quite expensive.
     */
    if (ERTS_MSACC_IS_ENABLED_CACHED_X()) {
        ERTS_MSACC_UPDATE_CACHE_X();
    }
    ERTS_MSACC_SET_STATE_CACHED_M_X(ERTS_MSACC_STATE_EMULATOR);
    if (ERTS_LIKELY(is_value(result))) {
        /*
         * Success. Store the result and return to the caller.
         */
        r(0) = result;
        CHECK_TERM(r(0));
        $return();
    } else if (c_p->freason == TRAP) {
        /*
         * Dispatch to a trap. When the trap is done, a jump
         * to the continuation pointer on the stack will be done.
         */
        SET_I(c_p->i);
        $DISPATCH();
    }

    /*
     * Error handling.  SWAPOUT is not needed because it was done above.
     */
    ASSERT(c_p->stop == E);
    I = handle_error(c_p, I, reg, &export->info.mfa);
    goto post_error_handling;
    //| -no_next
}

//
// Send is almost a standard call-BIF with two arguments, except for:
//   1. It cannot be traced.
//   2. There is no pointer to the send_2 function stored in
//      the instruction.
//

send() {
    Eterm result;

    if (!(FCALLS > 0 || FCALLS > neg_o_reds)) {
        /* If we have run out of reductions, we do a context
           switch before calling the bif */
        c_p->arity = 2;
        c_p->current = NULL;
        goto context_switch3;
    }

    PRE_BIF_SWAPOUT(c_p);
    c_p->fcalls = FCALLS - 1;
    result = erl_send(c_p, r(0), x(1));
    ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
    ERTS_REQ_PROC_MAIN_LOCK(c_p);
    PROCESS_MAIN_CHK_LOCKS(c_p);
    HTOP = HEAP_TOP(c_p);
    FCALLS = c_p->fcalls;
    if (ERTS_LIKELY(is_value(result))) {
        r(0) = result;
        CHECK_TERM(r(0));
    } else if (c_p->freason == TRAP) {
        $SAVE_CONTINUATION_POINTER($NEXT_INSTRUCTION);
        SET_I(c_p->i);
        SWAPIN;
        $DISPATCH();
    } else {
        goto find_func_info;
    }
}

nif_start() {
}

call_nif_early() {
    HEAVY_SWAPOUT;
    I = erts_call_nif_early(c_p, erts_code_to_codeinfo(I));
    HEAVY_SWAPIN;
    ASSERT(VALID_INSTR(*I));
    Goto(*I);
    //| -no_next
}

call_nif := nif_bif.call_nif.epilogue;
call_bif := nif_bif.call_bif.epilogue;

nif_bif.head() {
    Eterm nif_bif_result;
    Eterm bif_nif_arity;
    BifFunction vbf;
    ErlHeapFragment *live_hf_end;
    const ErtsCodeMFA *codemfa;
}

nif_bif.call_nif(Func, NifMod, DirtyFunc) {
    /*
     * call_nif is always first instruction in function:
     *
     * I[-3]: Module
     * I[-2]: Function
     * I[-1]: Arity
     * I[0]: &&call_nif
     * I[1]: Function pointer to NIF function
     * I[2]: Pointer to erl_module_nif
     * I[3]: Function pointer to dirty NIF. This is not used in this
     *       instruction, but dirty schedulers look at it.
     *
     * This layout is determined by the ErtsNativeFunc struct
     */

    (void)$DirtyFunc;

    ERTS_MSACC_SET_STATE_CACHED_M_X(ERTS_MSACC_STATE_NIF);

    codemfa = erts_code_to_codemfa(I);

    c_p->current = codemfa; /* current and vbf set to please handle_error */

    DTRACE_NIF_ENTRY(c_p, codemfa);

    HEAVY_SWAPOUT;

    PROCESS_MAIN_CHK_LOCKS(c_p);
    bif_nif_arity = codemfa->arity;
    ERTS_UNREQ_PROC_MAIN_LOCK(c_p);

    ASSERT(!ERTS_PROC_IS_EXITING(c_p));
    {
        typedef Eterm NifF(struct enif_environment_t*, int argc, Eterm argv[]);
        NifF* fp = vbf = (NifF*) $Func;
        struct enif_environment_t env;
        ASSERT(c_p->scheduler_data);
        live_hf_end = c_p->mbuf;
        ERTS_CHK_MBUF_SZ(c_p);
        erts_pre_nif(&env, c_p, (struct erl_module_nif*)$NifMod, NULL);

        ASSERT((c_p->scheduler_data)->current_nif == NULL);
        (c_p->scheduler_data)->current_nif = &env;

        nif_bif_result = (*fp)(&env, bif_nif_arity, reg);
        if (env.exception_thrown)
            nif_bif_result = THE_NON_VALUE;

        ASSERT((c_p->scheduler_data)->current_nif == &env);
        (c_p->scheduler_data)->current_nif = NULL;

        erts_post_nif(&env);
        ERTS_CHK_MBUF_SZ(c_p);

        PROCESS_MAIN_CHK_LOCKS(c_p);
        ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
        ERTS_MSACC_SET_STATE_CACHED_M_X(ERTS_MSACC_STATE_EMULATOR);
        ASSERT(!env.exiting);
        ASSERT(!ERTS_PROC_IS_EXITING(c_p));
    }

    DTRACE_NIF_RETURN(c_p, codemfa);
}

nif_bif.call_bif(Func) {
    /*
     * At this point, I points to the code[0] in the native function wrapper
     * for the BIF:
     *
     * code[-3]: Module
     * code[-2]: Function
     * code[-1]: Arity
     * code[0]: &&call_bif
     * code[1]: Function pointer to BIF function
     */

    if (!((FCALLS - 1) > 0 || (FCALLS - 1) > neg_o_reds)) {
        /* If we have run out of reductions, we do a context
           switch before calling the bif */
        goto context_switch;
    }

    codemfa = erts_code_to_codemfa(I);

    ERTS_MSACC_SET_BIF_STATE_CACHED_X(codemfa->module, (BifFunction)$Func);

    /* In case we apply process_info/1,2 or load_nif/1 */
    c_p->current = codemfa;
    $SET_CP_I_ABS(I);     /* In case we apply check_process_code/2. */
    c_p->arity = 0;       /* To allow garbage collection on ourselves
                           * (check_process_code/2, put/2, etc). */
    DTRACE_BIF_ENTRY(c_p, codemfa);

    SWAPOUT;
    ERTS_DBG_CHK_REDS(c_p, FCALLS - 1);
    c_p->fcalls = FCALLS - 1;
    vbf = (BifFunction)$Func;
    PROCESS_MAIN_CHK_LOCKS(c_p);
    bif_nif_arity = codemfa->arity;
    ASSERT(bif_nif_arity <= 4);
    ERTS_UNREQ_PROC_MAIN_LOCK(c_p);
    ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
    {
        ErtsBifFunc bf = vbf;
        ASSERT(!ERTS_PROC_IS_EXITING(c_p));
        live_hf_end = c_p->mbuf;
        ERTS_CHK_MBUF_SZ(c_p);
        nif_bif_result = (*bf)(c_p, reg, I);
        ERTS_CHK_MBUF_SZ(c_p);
        ASSERT(!ERTS_PROC_IS_EXITING(c_p) ||
               is_non_value(nif_bif_result));
        ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
        PROCESS_MAIN_CHK_LOCKS(c_p);
    }
    /* We have to update the cache if we are enabled in order
       to make sure no book keeping is done after we disabled
       msacc. We don't always do this as it is quite expensive. */
    if (ERTS_MSACC_IS_ENABLED_CACHED_X())
        ERTS_MSACC_UPDATE_CACHE_X();
    ERTS_MSACC_SET_STATE_CACHED_M_X(ERTS_MSACC_STATE_EMULATOR);
    DTRACE_BIF_RETURN(c_p, codemfa);
}

nif_bif.epilogue() {
    //| -no_next
    ERTS_REQ_PROC_MAIN_LOCK(c_p);
    ERTS_HOLE_CHECK(c_p);
    if (ERTS_IS_GC_AFTER_BIF_DESIRED(c_p)) {
        nif_bif_result = erts_gc_after_bif_call_lhf(c_p, live_hf_end,
                                                    nif_bif_result,
                                                    reg, bif_nif_arity);
    }
    SWAPIN;  /* There might have been a garbage collection. */
    FCALLS = c_p->fcalls;
    ERTS_DBG_CHK_REDS(c_p, FCALLS);
    if (ERTS_LIKELY(is_value(nif_bif_result))) {
        r(0) = nif_bif_result;
        CHECK_TERM(r(0));
        $RETURN();
        Goto(*I);
    } else if (c_p->freason == TRAP) {
        if (c_p->flags & F_HIBERNATE_SCHED) {
            c_p->flags &= ~F_HIBERNATE_SCHED;
            goto do_schedule;
        }
        SET_I(c_p->i);
        $DISPATCH();
    }
    {
        const BeamInstr *cp =
            (const BeamInstr*)erts_printable_return_address(c_p, E);
        ASSERT(VALID_INSTR(*cp));
        I = handle_error(c_p, cp, reg, c_p->current);
    }
    goto post_error_handling;
}

i_load_nif() {
    //| -no_next
    if (erts_try_seize_code_mod_permission(c_p)) {
        Eterm result;

        PRE_BIF_SWAPOUT(c_p);
        result = erts_load_nif(c_p, I, r(0), r(1));
        erts_release_code_mod_permission();
        ERTS_REQ_PROC_MAIN_LOCK(c_p);
        SWAPIN;

        if (ERTS_LIKELY(is_value(result))) {
            r(0) = result;
            $NEXT0();
        } else {
            static ErtsCodeMFA mfa = {am_erlang, am_load_nif, 2};
            c_p->freason = BADARG;
            I = handle_error(c_p, I, reg, &mfa);
            goto post_error_handling;
        }
    } else {
        /* Yield and try again */
        $SET_CP_I_ABS(I);
        SWAPOUT;
        c_p->current = NULL;
        c_p->arity = 2;
        goto context_switch3;
    }
}
